package com.pine.sunshineelder.eldernurselevel.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pine.sunshineelder.common.StringHelper;
import com.pine.sunshineelder.common.dao.ElderNursedDao;
import com.pine.sunshineelder.common.entity.ElderNursedEntity;
import com.pine.sunshineelder.common.exception.ThisSystemException;
import com.pine.sunshineelder.common.validator.ValidateHelper;
import com.pine.sunshineelder.eldernurselevel.ao.NursedAddAo;
import com.pine.sunshineelder.eldernurselevel.service.ElderNursedService;

@Service
public class ElderNursedServiceImpl implements ElderNursedService, StringHelper {
	@Autowired
	private ElderNursedDao edao;

	@Override
	public ElderNursedEntity addNursed(NursedAddAo ao) throws Exception {
		// 验证清理参数
		String nurselevelId = ValidateHelper.$("护理级别id", ao.getNurselevelId());
		String elderId = ValidateHelper.$("老人id", ao.getElderId());
		String createUserId = ValidateHelper.$("创建人id", ao.getCreateUserId());
		String changeReason = ValidateHelper.$("改变理由", ao.getChangeReason());
		String aideId = ValidateHelper.$("护工id", ao.getAideId());
		// 结果组装
		ElderNursedEntity ene = new ElderNursedEntity();
		String id = uuid();
		ene.setId(id);
		ene.setNurselevelId(nurselevelId);
		ene.setElderId(elderId);
		ene.setCreateUserId(createUserId);
		ene.setChangeReason(changeReason);
		ene.setAideId(aideId);
		edao.insert(ene);
		return ene;
	}

	@Override
	public void deleteNursed(String id) throws Exception {
		// 验证清理参数
		id = ValidateHelper.$("id", id);
		// 执行业务逻辑
		edao.delete(id);

	}

	@Override
	public ElderNursedEntity modeifyNused(String id, Map<String, String> ao) throws Exception {
		// 1验证清理参数
		id = ValidateHelper.$("id", id);
		// 2 执行业务逻辑
		// 传入id
		ElderNursedEntity ene = edao.selectById(id);
		if (ene == null) {
			throw new ThisSystemException("id.not-exisits", "非法id");
		}
		Map<String, Object> endMap = new HashMap<String, Object>();
		// 结束时间
		String endDate = trimAsNull(ao.get("endTime"));
		if (endDate != null) {
			// 时间类型转换,字符串转日期
			LocalDate newEndTime = LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
			// 修改旧对象
			ene.setEndTime(newEndTime);
			// 保存要修改的字段
			endMap.put("endTime", newEndTime);
		}
		// 改变理由
		String newChangeReasonString = trimAsNull(ao.get("changeReason"));
		// 修改旧对象
		ene.setChangeReason(newChangeReasonString);
		// 保存要修改的字段
		endMap.put("changeReason", newChangeReasonString);

		// 实际修改
		edao.update(id, endMap);
		// 组装业务结果
		return ene;

	}
}
